<?php
namespace app\util;


use app\traits\EnvTrait;

class MengChen
{

    use EnvTrait;

    const ENV_TEST = 'test';
    const ENV_PROD = 'prod';
    const GOODS_TYPE_ID = 55;
    const APP_ID = 10000403;
    const PROJECT_ID = 227000;

    private $appSecret = '8CA86F2F1E94488EB2B3EED9A67E8EAF';
    //private $appSecret = '3CF66EDCCA822221B7F07125DD68F73B';

    //private $appId = 10000403;

    private $appKeyArr = [
        'test' => '20081',
        'prod' => [
            'commit' => '20125',
            'query' => '20126',
        ]
    ];


    //下单接口 测试服
    const Test_URL_AREAS = 'https://app.10000.design/agent/api/areas';
    const Test_URL_SELECT_NUMBERS = 'https://app.10000.design/agent/api/numbers';
    const Test_URL_PRODUCT_LIST = 'https://app.10000.design/agent/api/products';
    const Test_URL_PRODUCT_PURCHASE = 'https://app.10000.design/agent/api/order';
    const Test_URL_PRODUCT_DETAIL = 'https://app.10000.design/agent/api/orderDetail';


    //下单接口 正式服
    const Pro_Trade_URL = 'http://op.ejcop.com/router';

    private $appId;
    private $productId;
    private $timestamp;

    public function __construct()
    {
        $this->appId = 10000403;
        $this->productId = 227000;
        //$this->timestamp = $timestamp;
    }

    //获取地区接口
    public function getAreas($data)
    {
        $data['appId'] = $this->appId;
        $data['productId'] = $this->productId;
        $data['timestamp'] = time();
        $sign = $this->makeSign($data);
        $data['sign'] = $sign;
        $result = Tools::curlPost(self::Test_URL_AREAS, $data,true);
        if ($result['code']==0) {
            return  $result['data'];
        } else {
            return ['code' => $result['code'], 'message' => $result['message'] ?? ''];
        }
    }

    //获取产品列表
    public function productList($data)
    {
        $data['appId'] = $this->appId;
        $data['productId'] = $this->productId;
        $data['timestamp'] = time();
        $sign = $this->makeSign($data);
        $data['sign'] = $sign;
        $result = Tools::curlPost(self::Test_URL_PRODUCT_LIST, $data,true);
        if ($result['code']==0) {
            return  $result['data'] ?? [];
        } else {
            return ['code' => $result['code'], 'message' => $result['message'] ?? ''];
        }
    }

    //下单
    public function purchase($data)
    {
        $data['appId'] = $this->appId;
        $data['productId'] = $this->productId;
        $data['timestamp'] = time();
        $sign = $this->makeSign($data);
        $data['sign'] = $sign;
        $result = Tools::curlPost(self::Test_URL_PRODUCT_PURCHASE, $data,true);
        if ($result['code']==0) {
            return ['code' => 0];
        } else {
            return ['code' => $result['code']??1, 'message' => $result['message'] ?? ''];
        }
    }

    //查询
    public function query($data)
    {
        $data['appId'] = $this->appId;
        $data['timestamp'] = time();
        $sign = $this->makeSign($data);
        $data['sign'] = $sign;
        $result = Tools::curlPost(self::Test_URL_PRODUCT_DETAIL, $data,true);
        if ($result['code']==0) {
            return  ['code' => 0 , 'data' => $result['data'] ?? []];
        } else {
            return ['code' => $result['code'], 'message' => $result['message'] ?? ''];
        }


    }

    //选号
    public function selectPhoneNum($data)
    {
        $data['appId'] = $this->appId;
        $data['productId'] = $this->productId;
        $data['timestamp'] = time();
        $sign = $this->makeSign($data);
        $data['sign'] = $sign;
        $result = Tools::curlPost(self::Test_URL_SELECT_NUMBERS, $data,true);
        if ($result['code']==0) {
            $numbers = array_column($result['data'], 'number');
            $phoneNums = json_encode($numbers);
            //return  ['code' => $result['code'], 'data' => $result['data'] ?? [] ];
            return  ['code' => $result['code'], 'data' => ['phoneNums' => $phoneNums] ];
        } else {
            return ['code' => $result['code'], 'message' => $result['message'] ?? ''];
        }
    }


    //验证号码是否被占用
    public function isOccupy($data)
    {
        $params = [
            //'appKey' => $this->appKey,
            'appKey' => $this->getAppKey(),
            'method' => $this->method,
            'locale' => $this->locale,
            'v' => $this->version,
            'messageFormat' => $this->messageFormat,
            'serialNumber' => $data['serialNumber'],
            'cityCode' => $data['cityCode'],
            'provinceCode' => $data['provinceCode'],
            'certCode' => $data['certCode'],
        ];

        $params = $this->makeSign($params);
        $result = Tools::curlPost($this->getUrl(), $params, false);

        if ($result['code'] === '0000') {
            return ['code' => 0];
        } else {
            return ['code' => $result['code'], 'message' => $result['message']];
        }

    }

    //验证号码是否被占用
    public function validate($data)
    {
        $params = [
            'appKey' => $this->getAppKey(),
            'method' => $this->method,
            'locale' => $this->locale,
            'v' => $this->version,
            'messageFormat' => $this->messageFormat,
            'params' => $data['params'],
            'chanId' => self::inEnvTesting() ? 20081 : 20125,
        ];

        $params = $this->makeSign($params);
        $result = Tools::curlPost($this->getUrl(), $params, false);
        if (isset($result['code']) && $result['code'] === '00000000') {
            return ['code' => 0];
        } else {
            return ['code' => $result['resData'][0]['gztCode'] ?? $result['code'] ?? 1 , 'message' =>  $result['resData'][0]['gztDesc']] ?? $result['message'] ?? '';
        }

    }


    /**
     * 获取签名
     */
    function makeSign($params)
    {
        ksort($params);
        $buff = "";
        foreach ($params as $k => $v) {
            if ($k != "signature"  && !(strlen($v) == 0) && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        $buff .= $this->appSecret;
//        dump($buff);die;
        return strtolower(md5($buff));
    }



    private function getAppKey($type = 'commit')
    {
        $env = env('APP_ENV');
        return self::inEnvTesting() ? $this->appKeyArr[$env] : $this->appKeyArr[$env][$type];
    }

    private function getSecret($type = 'commit')
    {
        $env = env('APP_ENV');
        return self::inEnvTesting() ? $this->appSecretArr[$env] : $this->appSecretArr[$env][$type];
    }

    private function getUrl()
    {
        return self::inEnvTesting() ? self::Test_Trade_URL : self::Pro_Trade_URL;
    }
}
